//
//  ChoseViewController.m
//  UIA段项目 墨家天气
//
//  Created by dllo on 15/8/25.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ChoseViewController.h"
#import "CityModel.h"
#import "URL.h"
#import "GDataXMLNode.h"
#import "ChooseCityLayout.h"
#import "ChooseCityCell.h"
#import "AddCity.h"
#import "NovelDataBase.h"
#import "NovelModel.h"
#import "URL.h"
@interface ChoseViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ChoseViewControllerDelegate,UITextFieldDelegate, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic,retain)UIView *headerView;
@property (nonatomic, retain)UISearchBar *search;
@property (nonatomic, retain)UIView *smallView;
@property (nonatomic, retain)UITableView *smallTableView;
@property (nonatomic, retain)NSMutableArray *nameArray;
@property (nonatomic, retain)NSMutableArray *smallArray;
@property (nonatomic, retain)NSMutableArray *handleArr;
@property (nonatomic,retain)UICollectionView *collect;

@end

@implementation ChoseViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.nameArray = [NSMutableArray array];
        self.smallArray = [NSMutableArray array];
        self.handleArr = [NSMutableArray array];
    }
    return self;
}

-(void)dealloc
{
    [_headerView release];
    [_search release];
    [_smallArray release];
    [_smallTableView release];
    [_nameArray release];

    [_handleArr release];
    [_collect release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self addHandle];
    [self addCollectionView];
    [self addSearchView];
    [self addHeaderView];
    [self addWhileLineLable];

}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.arr = [NSArray array];
        self.dateArr = [NSArray array];
    }
    return self;
}
- (void)addHandle
{
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"City" ofType:@"plist"];
    
    self.arr = [NSArray arrayWithContentsOfFile:path];
    for (int i = 0; i < self.arr.count; i++) {
        [self.nameArray addObject:[[self.arr objectAtIndex:i] objectForKey:@"name"]];
    }

  
    
    
}
- (void)addSearchView
{
  

    self.search = [[UISearchBar alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 300 * OffWidth) / 2, 100 * OffHeight, 300 * OffWidth, 35 * OffHeight)];
    [self.view  addSubview:self.search];
 
    [self.search release];
    self.search.placeholder = @"请输入城市,拼音或英文";
    self.search.showsCancelButton = YES;
    self.search.delegate = self;
    self.search.barTintColor = [UIColor whiteColor] ;
  
    
    
}
- (void)addCollectionView
{
    
    
    ChooseCityLayout *flow = [[ChooseCityLayout alloc]init];
//    flow.itemSize = CGSizeMake(100 * OffWidth,100 * OffHeight);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collect = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flow];
    _collect.delegate = self;
    _collect.dataSource = self;
    [_collect registerClass:[ChooseCityCell class] forCellWithReuseIdentifier:@"fff"];
    
    
    UIImageView *imageV = [[UIImageView alloc]init];
    imageV.image = [UIImage imageNamed:@"shui.jpg"];
    [_collect setBackgroundView:imageV];
    [self.view addSubview:_collect];
  
    
    UIBlurEffect *ef = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effV = [[UIVisualEffectView alloc]initWithEffect:ef];
    effV.frame = [UIScreen mainScreen].bounds;
    [imageV addSubview:effV];
    

}

- (void)addWhileLineLable
{
    UILabel *line  = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 300 * OffWidth) / 2, self.search.frame.size.height + 220 * OffHeight, self.search.frame.size.width, 1 * OffHeight)];
    line.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:line];
    [line release];
    
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 300 * OffWidth) / 2, 200 * OffHeight, 100 * OffWidth, 30 * OffHeight)];
    lable.text = @"热门城市";
    lable.font = [UIFont systemFontOfSize:19 * OffWidth];
    lable.textColor = [UIColor whiteColor];
    [self.view addSubview:lable];
    [lable release];
    
    
}

- (void)createSmallView
{
    self.smallView = [[UIView alloc]initWithFrame:CGRectMake(0, 160 * OffHeight, self.view.frame.size.width, self.view.frame.size.height - 370 * OffHeight)];
    [self.view addSubview:self.smallView];
    self.smallView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.7];
    [self.smallView release];
}


- (void)createSmallTableView
{
    self.smallTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.smallView.frame.size.height) style:UITableViewStylePlain];
    [self.smallView addSubview:self.smallTableView];
    [self.smallTableView release];
    self.smallTableView.delegate = self;
    self.smallTableView.dataSource = self;
    self.smallTableView.backgroundColor = [UIColor clearColor];
    self.smallTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.handleArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIder = @"dddd";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIder];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIder];
       
    }
    

    if (self.handleArr.count != 0) {        
    cell.textLabel.text = [[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"name"];
        cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.text = [[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"tip"];
    cell.detailTextLabel.textColor = [UIColor grayColor];
    }
    
    BOOL temp = [NovelDataBase selectWith:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"name"]];
    BOOL temp1 = [NovelDataBase selectWithId:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"id"]];

    
    if (temp || temp1) {
    cell.textLabel.textColor = [UIColor grayColor];
   
    }

    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    BOOL temp = [NovelDataBase selectWith:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"name"]];
    BOOL temp1 = [NovelDataBase selectWithId:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"id"]];


    if (temp || temp1) {
        
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 120 * OffWidth) / 2, 250 * OffHeight, 120 * OffWidth, 30 * OffHeight)];
        lable.text = @"不能重复添加城市";
        lable.textAlignment = 0;
        lable.font = [UIFont boldSystemFontOfSize:15 * OffWidth];
        lable.textColor = [UIColor whiteColor];
        [self.view addSubview:lable];
        
        
        [UIView animateWithDuration:3 animations:^{
            
            lable.alpha = 0.1;
            
        } completion:^(BOOL finished) {
            
            [lable removeFromSuperview];
        }];
        

        
        
        
    }else{
    int bb = arc4random() % 20;
    NSString *backImage = [[self.arr objectAtIndex:bb]objectForKey:@"num"];
    [self.delegata sendNameMessage:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"name"] backImage:backImage cityId:[[self.handleArr objectAtIndex:indexPath.row] objectForKey:@"id"]];
    AddCity *add = [[AddCity alloc]init];
    [self dismissViewControllerAnimated:add completion:nil];
    }
    
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self createSmallView];
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    [self.smallView removeFromSuperview];
}

// 输入文字时改变
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self.smallTableView removeFromSuperview];
    [self createSmallTableView];
    [self.view bringSubviewToFront:self.smallTableView];
    [self.smallArray removeAllObjects];

    searchText = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:@"107" forKey:@"act"];
            [dic setObject:searchText forKey:@"word"];
            [dic setObject:@"4" forKey:@"mt"];
            [dic setObject:@"3.11.2" forKey:@"sv"];
            [dic setObject:@"4.4.4" forKey:@"osv"];
            [dic setObject:@"868033019886185" forKey:@"imei"];
            [dic setObject:@"M040" forKey:@"dm"];
            [dic setObject:@"60" forKey:@"nt"];
            [dic setObject:@"401FFD8CECB45C1FB7D40679012FC227%7C581688910330868" forKey:@"CUID"];
            [dic setObject:@"115" forKey:@"pid"];
            [dic setObject:@"1010969b" forKey:@"chl"];



            [URL conectionWithUrl:@"http://tq.91.com/api/" dic:dic block:^(NSData *data) {
                
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
                
                self.handleArr = [dic objectForKey:@"items"];
             
                [self.smallTableView reloadData];
            }];
            
    
}




- (void)addHeaderView
{
    
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60 * OffHeight)];
    _headerView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    _headerView.alpha = 0.8;
    [self.view addSubview:_headerView];
    
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeSystem];
    [buttonBack setBackgroundImage:[UIImage imageNamed:@"houtui.png"] forState:UIControlStateNormal];
    buttonBack.frame = CGRectMake(0, 25 * OffHeight,30 * OffWidth, 25 * OffHeight);
    [buttonBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];    
    [self.headerView addSubview:buttonBack];
    
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(30 * OffWidth, 22 * OffHeight, 100 * OffWidth, 30 * OffHeight)];
    lable.text = @"热门城市";
    lable.font = [UIFont systemFontOfSize:17 * OffWidth];
    lable.textColor = [UIColor whiteColor];
    [self.headerView addSubview:lable];
    
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    
    ChooseCityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"fff" forIndexPath:indexPath];
    
    
    cell.lable.text = [[self.arr objectAtIndex:indexPath.item] objectForKey:@"name"] ;
    
    
    
    BOOL temp = [NovelDataBase selectWith:[[self.arr objectAtIndex:indexPath.item] objectForKey:@"name"]];
    if (temp) {
        cell.lable.textColor = [UIColor cyanColor];
        [cell.lable resignFirstResponder];
    }
    return cell;
    
    
    
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *name = [[self.arr objectAtIndex:indexPath.item] objectForKey:@"name"];
    int bb = arc4random() % 20;
    NSString *backImage = [[self.arr objectAtIndex:bb]objectForKey:@"num"];
    NSString *cid = [[self.arr objectAtIndex:indexPath.item] objectForKey:@"number"];
    AddCity *add = [[AddCity alloc]init];
    
    BOOL temp = [NovelDataBase selectWith:[[self.arr objectAtIndex:indexPath.item] objectForKey:@"name"]];
    if (temp) {
      
        
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 120 * OffWidth) / 2, 500 * OffHeight, 120 * OffWidth, 30 * OffHeight)];
        lable.text = @"不能重复添加城市";
        lable.textAlignment = 0;
        lable.font = [UIFont boldSystemFontOfSize:15 * OffWidth];
        lable.textColor = [UIColor blackColor];
        [self.view addSubview:lable];
        
        
        [UIView animateWithDuration:3 animations:^{
            
            lable.alpha = 0.1;
            
        } completion:^(BOOL finished) {
            
            [lable removeFromSuperview];
        }];
        
        
        
        
    }else{

  
    [self.delegata sendNameMessage:name backImage:backImage cityId:cid];
    [self dismissViewControllerAnimated:add completion:nil];
    
    }
}

- (void)back:(UIButton *)button
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//回收键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
